<form class="form-horizontal" id="sendimg" action="/italiaCives/segnalazione/addpic" method=POST enctype=multipart/form-data  role="form_invio_immagine"></form>
<form class="form-horizontal" id="ae_form" action="/italiaCives/segnalazione/Create" method=POST role="form">
<input type="hidden" name="id" id="id" value="{{pageData['dao'].id}}"/>
<input type='hidden' name='formSubmission' id='mySubmission'/>
<!-- TAB 1 -->
  {% if pageData["dao"].id %}
<ul class="nav nav-tabs" role="tablist" id="myTab">
  <li class="active "><a href="#dataPrincipali" role="tab" data-toggle="tab">Dati principali</a></li>
  <li ><a href="#percorsoSegnalazione" role="tab" data-toggle="tab">Storico</a></li>
</ul>
    {% endif %}
<div class="clearfix"></div>
<div class="tab-content">
  <div class="tab-pane active" id="dataPrincipali">
      {% if pageData["dao"].numero %}
      <div class="form-group">
            <label class="col-sm-3 col-lg-3 control-label" >Numero: {{pageData["dao"].numero|nonone}}</label>
        </div>
        {% endif %}
        <div class="form-group" title="">
            <label class="col-sm-3 col-lg-3 control-label" for="denominazione">Titolo:</label>
            <div class="col-sm-9 col-lg-9">
                <input class="form-control validate[required]" type="text" id="denominazione" name="denominazione" value='{{pageData["dao"].denominazione|nonone}}'/>
            </div>
        </div>
            <div class="form-group">
                <label class="col-sm-3 col-lg-3 control-label" for="id_tipo_segnalazione" >Argomento:</label>
                <div class="col-sm-9 col-lg-9">
                    <select id="id_tipo_segnalazione" name="id_tipo_segnalazione" class="validate[required]">
                        {% for t in pageData['tiposegnalazione'] %}
                            <option value="{{t.id}}" {{ 'selected="selected"' if t.id == pageData["dao"].id_tipo_segnalazione}}  >{{t.denominazione}} </option>
                        {% endfor %}
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 col-lg-3 control-label" for="id_tipo_segnalazione" >Priorità:</label>
                <div class="col-sm-9 col-lg-9">
                    <select id="id_priorita_segnalazione" name="id_priorita_segnalazione" class="validate[required]">
                        {% for t in pageData['prioritasegnalazione'] %}
                            <option value="{{t.id}}" {{ 'selected="selected"' if t.id == pageData["dao"].id_priorita_segnalazione}}  >{{t.denominazione}} </option>
                        {% endfor %}
                    </select>
                </div>
            </div>
            <div class="form-group" title="">
                <label class="col-sm-3 col-lg-3 control-label" for="descrizione">Descrizione:</label>
                <div class="col-sm-9 col-lg-9">
                    <div id="summernote_segnalazione">{{pageData["dao"].descrizione|nonone}}</div>
                </div>
            </div>
            {% if pageData["oper"] and pageData["oper"].tipo_operatore|lower == "amministratore" %}
            <div class="form-group">
                <label class="col-sm-3 col-lg-3 control-label" for="id_stato_segnalazione" >Stato :</label>
                <div class="col-sm-9 col-lg-9">
                    <select id="id_stato_segnalazione" name="id_stato_segnalazione" class="validate[required]">
                        {% for t in pageData['statosegnalazione'] %}
                            <option value="{{t.id}}" {{ 'selected="selected"' if t.id == pageData["dao"].id_stato_segnalazione}}  >{{t.denominazione}} </option>
                        {% endfor %}
                    </select>
                </div>
            </div>

            <div class="form-group" title="">
                <label class="col-sm-3 col-lg-3 control-label" for="descrizione">Note del cambiamento:</label>
                <div class="col-sm-9 col-lg-9">
                    <textarea class="form-control" type="text" id="note "name="note" rows="4" cols="45"></textarea>
                </div>
            </div>
            {% endif %}

<div class="form-group">
<div class="col-sm-9 col-lg-9 col-sm-offset-3">
        <a type="button" class="btn btn-lg btn-success" id="geolocal">
  <i class="fa fa-map-marker fa-2x pull-left"></i>Aggiungi la tua<br>posizione<br>alla segnalazione</a>
  <div id="posizione_trovata"><p style="color:red;"><b>Posizione acquisita, grazie</b></p></div>
   <input type="hidden" name="maplat" id="lat" value="{{pageData["dao"].lat|nonone}}" />
    <input type="hidden" name="maplng" id="lng" value="{{pageData["dao"].lng|nonone}}" />
    </div>
</div>
<div class="form-group">
<div class="col-sm-9 col-lg-9 col-sm-offset-3">
        <a type="button" class="btn btn-lg btn-primary" id="show_image" >

                        {% if pageData['dao'].immagine_thumb %}
<i class="fa fa-camera fa-2x pull-left"></i>Modifica l'<br>immagine<br>della segnalazione</a>
                        {% else %}
<i class="fa fa-camera fa-2x pull-left"></i>Aggiungi una<br>immagine<br>alla segnalazione</a>
                        {% endif %}
    </div>
 </div>
                {% if pageData['dao'].immagine_thumb %}
                <div class="row">

                <div class="col-sm-12 col-lg-12 col-sm-offset-3 old_preview"><a title="{{pageData['dao'].denominazione}}"><img style='max-width: 200px' src="data:image/png;base64,{{pageData['dao'].immagine_thumb}}"  /></a></div>
                 </div>
                  {% endif %}

        <div class="col-sm-9 col-lg-9 col-sm-offset-3 immagine_up">
<!--
FORM IMMAGINI
-->
                    <input type="hidden" name="id_segna" id="id_segna" value="{{pageData['dao'].id}}" form="sendimg" />
                    <div>
<!--
                        <div><label for="image_file">Seleziona una immagine da abbinare</label></div>
-->
                        <span class="btn btn-default btn-file btn-warning" >
                                <br>Seleziona Immagine<br><br> <input type="file" class="bottone_scegli" form="sendimg" name="image_file" id="image_file" onchange="fileSelected();" />

                        </span><br>
                        <span class="btn btn-default btn-file btn-danger" >
                                <br>Scatta nuova immagine<br><br> <input type="file" form="sendimg" name="image_foto" id="image_foto" onchange="fileSelected2();" accept="image/*" capture="camera" />

                        </span>

                    </div>
                    <div id="error">You should select valid image files only!</div>
                    <div id="error2">An error occurred while uploading the file</div>
                    <div id="abort">The upload has been canceled by the user or the browser dropped the connection</div>
                    <div id="warnsize">Your file is very big. We can't accept it. Please select more small file</div>

                    <div id="progress_info">
                        <div id="progress"></div>
                        <div id="progress_percent">&nbsp;</div>
                        <div class="clear_both"></div>
                        <div>
                            <div id="speed">&nbsp;</div>
                            <div id="remaining">&nbsp;</div>
                            <div id="b_transfered">&nbsp;</div>
                            <div class="clear_both"></div>
                        </div>
                        <div id="upload_response"></div>
                    </div>
          <img id="preview" />
          <div class="clearfix"></div>
                              <div id="fileinfo">
                        <div id="filename"></div>
                        <div id="filesize"></div>
                        <div id="filetype"></div>
                        <div id="filedim"></div>
                    </div>
          <div class="clearfix"></div>
          <br>
                             <div>
                        <input type="button" id="carica_immagine" class="btn btn-danger bottone_carica" value="Carica Immagine" form="sendimg" onclick="startUploading()" />
                    </div>
         </div>


  </div> <!-- FINE primo pane-tab -->
  <div class="tab-pane" id="percorsoSegnalazione">
    <br /><br /> <br />

  <div class="infinite-container">
        {% for a in pageData["percorso"] %}
        <div class="infinite-itemmm">
<div class="row">
    <div class="col-xs-12 col-md-12 col-lg-12 col-sm-12">
        <div class="panel panel-danger">
            <div class="panel-heading">
                [#{{pageData["dao"].numero}}] <strong>{{a.data_modifica|datetimeformat}}</strong>
            </div>
        <div class="panel-body">
                <div class="row">
                    <div class="col-sm-12 col-lg-12"><b>Tipo:</b> {{ a.tipo_segnalazione|nonone }}</div>
                 </div>
                 <div class="row">
                    <div class="col-sm-12 col-lg-12"><b>Priorità:</b> {{ a.priorita_segnalazione|nonone }}</div>
                 </div>
                 <div class="row">
                    <div class="col-sm-12 col-lg-12"><b>Stato:</b> {{ a.stato_segnalazione|nonone }}</div>
                 </div>
                <div class="row">
                    <div class="col-sm-12 col-lg-12"><b>Operatore:</b> {{ a.operatore|nonone }}</div>
                 </div>
        </div>
        <div class="panel-footer">
            <b>Note:</b> {{ a.note|nonone }}
        </div>
        </div>
    </div>
</div>
</div>
        {% endfor %}

{% if pageData['page'] != 0 %}
    <a href="/italiaCives/segnalazioni/{{pageData['page']}}" class="infinite-more-link"></a>
{% endif %}
</div>

  </div>

</div>


  <div class="clearfix"></div>
  <br>
<div class="form-group" title="Bottoni di salvataggio e reset del form">
        <div class="col-sm-9 col-lg-9 col-sm-offset-3">
            <input class="btn btn-primary" type="submit" value="&nbsp;&nbsp;&nbsp;Invia&nbsp;&nbsp;&nbsp;" name="add"/>
            <input class="btn btn-danger" type="button"  value="&nbsp;&nbsp;&nbsp;Chiudi&nbsp;&nbsp;&nbsp;" name="chiudi" id="chiudi_edit"/>
         </div>
    </div>

</form>



<script src="/tpl/ic/js/summernote.min.js"></script>
<script src="/tpl/ic/js/summernote-it-IT.js"></script>
<script>
$(document).ready(function(){

$("#show_image").click(function(event) {
    $(".immagine_up").show(600)
    $(".bottone_carica").hide();
    });
$("#image_file").click(function(event) {
    var id = $("#id").val()
    if ( id != "") {
         $(".old_preview").hide(600)
        }
    //alert(id);
    });

$(".immagine_up").hide()

$("#ae_form").submit(function() {
    $("#mySubmission").val($('#summernote_segnalazione').code());
    var url = "/italiaCives/segnalazione/Create"; // the script where you handle the form input.

    $.ajax({
           type: "POST",
           url: url,
           data: $("#ae_form").serialize(), // serializes the form's elements.
           success: function(data)
           {
            msg = $.parseJSON(data);
            if (msg["result"] == "OK") {
                id = msg["id"]
                //alert(id);
                $("#id_segna").val(id);
                var a = $("#carica_immagine").click()
                //console.log(a)
                //alert("Latua tua segnalazione è stata correttamente salvata\n Grazie");
                //setTimeout("window.location.href='/italiaCives/dashboard';",1000);
            } else {
                    alert("C'è stato un errore nella segnalazione, controlla")


            }
              //alert(data); // show response from the php script.
           }
         });

    return false; // avoid to execute the actual submit of the form.
});



$("#chiudi_edit").click(function(event) {
    $("#new_dao").click()
    });

$('#summernote_segnalazione').summernote({
    lang: 'it-IT',
     //airMode: true,
  toolbar: [
    //[groupname, [button list]]

    //['style', ['bold', 'italic', 'underline', 'clear','color']],
    //['font', ['strikethrough']],
    //['fontsize', ['fontsize']],
    //['color', ['color']],
    //['para', ['ul', 'ol', 'paragraph']],
    //['height', ['height']],
    //['misc',['undo','redo']]
  ]
});


$("#posizione_trovata").hide()
$("#geolocal").click(function(event) {
navigator.geolocation.getCurrentPosition(
    gotPosition,
    errorGettingPosition,
    {'enableHighAccuracy':true,'timeout':10000,'maximumAge':0}
    );
    });

$('#myTab').click(function (e) {
  e.preventDefault()
  $(this).tab('show')
})

//$( "#ae_form" ).validationEngine({
                    //prettySelect : true,
                    //useSuffix: "_chosen",
                //});
//$( "#id_tipo_segnalazione" ).chosen({
                    //width: '100%',
                    //disable_search:true,
                    //allow_single_deselect: true})
//$( "#id_priorita_segnalazione" ).chosen({
                    //width: '100%',
                    //disable_search:true,
                    //allow_single_deselect: true})
//$( "#id_stato_segnalazione" ).chosen({
                    //width: '100%',
                    //disable_search:true,
                    //allow_single_deselect: true})


function gotPosition(pos)  {
        var outputStr =
            "latitude:"+ pos.coords.latitude +"\n"+
            "longitude:"+ pos.coords.longitude +"\n"+
            "accuracy:"+ pos.coords.accuracy +"\n"+

            "altitude:"+ pos.coords.altitude +"\n"+
            "altitudeAccuracy:"+ pos.coords.altitudeAccuracy +"\n"+
            "heading:"+ pos.coords.heading +"\n"+
            "speed:"+ pos.coords.speed +"";

            //alert(outputStr);
            $('input#lat').val( pos.coords.latitude );
            $('input#lng').val( pos.coords.longitude );
            $("#posizione_trovata").show(800)

}


//function gotPosition(pos)  {
        //var outputStr =
            //"latitude:"+ pos.coords.latitude +"\n"+
            //"longitude:"+ pos.coords.longitude +"\n"+
            //"accuracy:"+ pos.coords.accuracy +"\n"+

            //"altitude:"+ pos.coords.altitude +"\n"+
            //"altitudeAccuracy:"+ pos.coords.altitudeAccuracy +"\n"+
            //"heading:"+ pos.coords.heading +"\n"+
            //"speed:"+ pos.coords.speed +"";

            ////alert(outputStr);
            //$('input#lat').val( pos.coords.latitude );
            //$('input#lng').val( pos.coords.longitude );
    //$("#map_canvas").gmap3({
        //marker:{
            //values:[ {latLng:[pos.coords.latitude,pos.coords.longitude]}],
            //options:{draggable: true },
            //events:{
                //dragend: function(marker, event){
                //$('input#lat').val( marker.position.lat() );
                //$('input#lng').val( marker.position.lng() );
                        //$(this).gmap3({
          //getaddress:{
            //latLng:marker.getPosition(),
            //callback:function(results){
              //var map = $(this).gmap3("get"),
                //infowindow = $(this).gmap3({get:"infowindow"}),
                //content = results && results[1] ? results && results[1].formatted_address : "no address";
              //if (infowindow){
                //infowindow.open(map, marker);
                //infowindow.setContent(content);
              //} else {
                //$(this).gmap3({
                  //infowindow:{
                    //anchor:marker,
                    //options:{content: content}
                  //}
                //});
              //}
            //}
          //}
        //});
                //}
            //},
            //},

        //map:{
        //options:{ zoom: 14 }
        //}
        //});
    //}

function errorGettingPosition(err) {
        if(err.code == 1) {
            alert("Non hai autorizzato la geolocalizzazione");
        } else if(err.code == 2) {
            alert("Posizione non disponibile");
        } else if(err.code == 3) {
            alert("Timeout");
        } else {
            alert("ERRORE:" + err.message);
        }
    }

 });
</script>
